package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApUserSearch;
import com.heima.search.service.IApUserSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: itheima
 * @create: 2022-08-09 14:38
 */
@Service
public class ApUserSearchServiceImpl implements IApUserSearchService {


    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 保存用户搜索历史 存入MongoDB中
     *
     * @param dto
     * @param userId
     */
    @Override
    @Async("leadnewsExecutor")
    public void save(ApArticleSearchDto dto, Integer userId) {
        //1.根据关键字查询搜索历史是否存在
        Query query = new Query();
        //addCriteria增加查询条件 Criteria.where("查询字段名称")
        query.addCriteria(Criteria.where("userId").is(userId));
        query.addCriteria(Criteria.where("keyword").is(dto.getSearchWords()));
        long count = mongoTemplate.count(query, ApUserSearch.class);
        //2.如果为空则执行保存
        if (count == 0) {
            ApUserSearch apUserSearch = new ApUserSearch();
            apUserSearch.setUserId(userId);
            apUserSearch.setKeyword(dto.getSearchWords());
            apUserSearch.setEquipmentId(dto.getEquipmentId());
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
        } else {
            //3.如果有值更新时间
            //3.1 构建更新条件-使用上方查询条件即可
            //3.2 构建更新内容
            Update update = new Update();
            update.set("createdTime", new Date());
            mongoTemplate.updateFirst(query, update, ApUserSearch.class);
        }
    }


    /**
     * 加载用户搜索历史 前五条记录
     *
     * @param dto 查询条件
     * @return
     */
    @Override
    public ResponseResult load(ApArticleSearchDto dto) {
        User user = UserThreadLocalUtil.get();
        //1.构建查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        //设置查询分页信息 只查询五条记录
        query.with(PageRequest.of(0, 5));
        //设置排序
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));

        //2.执行分页查询
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);
    }

    /**
     * 删除历史搜索记录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delete(ApArticleSearchDto dto) {
        List<ApUserSearch> hisList = dto.getHisList();
        if (!CollectionUtils.isEmpty(hisList)) {
            //获取文档ID集合
            List<String> idsList = hisList.stream().map(ApUserSearch::getId).collect(Collectors.toList());
            //构建删除调借
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").in(idsList));
            //执行删除
            mongoTemplate.remove(query, "apUserSearch");
        }
        return ResponseResult.okResult();
    }
}
